<?php

	namespace app\timer\behavior;

	use think\Queue;

	class Sec{

		public function run(){
			$times = config('timer.alert_times');
			$times_text = config('timer.alert_times_text');

			if(is_array($times)){
				foreach($times as $k=>$secend){
					$secend_text = $times_text[$k];
					$this->startTask($secend, $secend_text, $k+1);
				}
			}
		}

		protected function startTask(int $secend, string $secend_text, int $alert_index, $offset = 0)
		{
			$limit = 1000;
			$thisModel = model('\app\admin\model\workteam\Task');
			$startTime = time() + $secend;

			$where = [
				't.alert_time_auto' => ['>', $secend],
				't.start_time' => ['<=', $startTime],
				't.status' => 0,
				't.admin_id' => ['<>', 0],
			];

			//寻找独立通知的项目【一个员工只推一个通知，不然如果多项目多任务就会出现很多通知。】
			/*$lists_row = $thisModel->alias("t")->join("workteam_project p",'p.id =t.project_id')
				->field('t.*,GROUP_CONCAT(t.id) as task_ids,GROUP_CONCAT(CONCAT_WS(' - ',p.`name`,t.`name`)) as task_name,p.dd_webhook,p.wx_webhook ')
				->where($where)->where('alert_minute','=','0')
				->fetchSql(false)->group('t.admin_id')->order('id asc')->limit($offset, $limit)->select();*/
			$lists_row = $thisModel->alias("t")->join("workteam_project p",'p.id =t.project_id')
				->field('t.id,t.admin_id,t.admin_ids,t.`name` as task_name,p.`name` as project_name,t.start_time,p.dd_webhook,p.wx_webhook')
				->where($where)->where('alert_minute','=','0')
				->fetchSql(false)->order('id asc')->limit($offset, $limit)->select();

			if ($lists_row && count($lists_row)) {
				$ids = [];
				foreach ($lists_row as $row) {
					$row['time_text'] = $secend_text;
					$row['alert_index'] = $alert_index;
					$row['admin_ids'] = $row->admin_id.','.$row->admin_ids;
					$row['link'] = config('admin.crm_url').url('workteam/task/edit',['ids'=>$row->id]);
					$row['key'] = 'notice_task_start';//任务即将开始模板
					//通知队列
					Queue::push('addons\workteam\library\notice\queue\TaskJob', $row);

					$ids[] = $row->id;
				}
				// 更新推送等级
				$thisModel->where(['id' => ['in', $ids]])->update(['alert_time_auto' => $secend]);
			}

			if ($lists_row && count($lists_row)) {
				$offset = $offset + $limit;
				echo " start task".$offset.PHP_EOL;
				unset($lists_row,$lists);
				return $this->startTask($secend, $secend_text, $alert_index, $offset);
			}else{
//				echo "done".PHP_EOL;
			}

			return;
		}
	}